#!/usr/bin/env python
# -*- coding: utf-8 -*-

from twisted.internet import protocol, reactor
import SocketTools
import RobotHandle

class RobotConnection(protocol.Protocol):
    def __init__(self, factory):
        self.tools = SocketTools.StructProtocol()
        self.money = 10000000
        self.freeze = 0
        self.market_value = 0
        self.position = dict()
        self.factory = factory

    def get_fund_id(self):
        return '130000001'

    def set_market_value(self, market_value):
        self.market_value = market_value

    def get_market_value(self):
        return self.market_value

    def set_freeze(self, freeze):
        self.freeze = freeze

    def get_freeze(self):
        return self.freeze

    def set_money(self, money):
        self.money = money

    def get_money(self):
        return self.money

    def get_proto_list(self):
        return self.factory.get_protocol_list()

    def dataReceived(self, data):
        self.tools.putData(data)
        while 1:
            message = self.tools.getOnce()
            if message:
                try:
                    ret = RobotHandle.Handle(message, self)
                except:
                    print 'msg error', message
                    continue

                self.transport.write(self.tools.pack(ret[0], ret[1]))
            else:
                break
        # self.transport.write(data)

class RobotFactory(protocol.Factory):
    protocol_list = list()
    def buildProtocol(self, addr):
        proto = RobotConnection(self)
        self.protocol_list.append(proto)
        return proto

    def get_protocol_list(self):
        return self.protocol_list

reactor.listenTCP(9876, RobotFactory())
reactor.run()